package com.example.servicebind;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;


import com.example.servicebind.service.DemoService;


public class MainActivity extends AppCompatActivity {

    /**
     * 定义一个用于消息交互的binder对象
     */
    private DemoService.MyBinder myBinder = null;

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.i("MainActivity", "===========service connected=========");
            if (iBinder != null) {
                myBinder = (DemoService.MyBinder) iBinder;
            }
        }

        /**
         * 1、onServiceDisconnected() 在连接正常关闭的情况下是不会被调用的.
         * 2、该方法只在Service 被破坏了或者被杀死的时候调用. 例如, 系统资源不足, 要关闭一些Services,
         * 刚好连接绑定的 Service 是被关闭者之一,  这个时候onServiceDisconnected() 就会被调用.
         *
         * @param componentName
         */
        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.i("MainActivity", "===========service disconnected=========");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button bindBtn = findViewById(R.id.bind_btn);

        Button getMsgBtn = findViewById(R.id.get_msg_btn);

        Button unbindBtn = findViewById(R.id.unbind_btn);

        bindBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, DemoService.class);
                //绑定service
                bindService(intent, sc, Service.BIND_AUTO_CREATE);
            }
        });

        //只要使用了bindService，不管之后是否解绑和停止服务，都可以调用服务中的方法
        getMsgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("MainActivity", myBinder.getMsg());
            }
        });

        unbindBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //解绑service
                unbindService(sc);
            }
        });
    }
}